package com.example.partner.fragment.find;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.partner.R;
import com.example.partner.adapter.find.MyPostsAdapter;
import com.example.partner.adapter.find.PostAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.listener.EndlessScrollListener;
import com.example.partner.model.domain.Post;
import com.example.partner.service.PostService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyPublishFragment extends Fragment {
    private List<Post> postList = new ArrayList<>(); // 定义列表用于保存所有帖子数据
    private MyPostsAdapter adapter; // 适配器
    private RecyclerView recyclerView;
    private int current = 1;
    private SwipeRefreshLayout swipeRefreshLayout;

    public MyPublishFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_my, container, false);
        // 在这里处理推荐页面的布局和数据显示，可以使用RecyclerView等组件
        recyclerView = rootView.findViewById(R.id.recyclerViewMy);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyPostsAdapter(postList,requireContext());
        recyclerView.setAdapter(adapter);
        loadMoreData();
        EndlessScrollListener endlessScrollListener = new EndlessScrollListener(layoutManager, new EndlessScrollListener.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                // 在这里更新 current，并执行加载更多的操作
                current++;
                loadMoreData();
            }
        });
        recyclerView.addOnScrollListener(endlessScrollListener);
        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            refreshData();
        });
        return rootView;
    }

    private void loadMoreData(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        SharedPreferences sharedPreferences = requireContext().getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        Call<BaseResponse<List<Post>>> call = postService.queryMyPost(current,userId);
        call.enqueue(new Callback<BaseResponse<List<Post>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<Post>>> call, Response<BaseResponse<List<Post>>> response) {
                if (response.isSuccessful()) {
                    List<Post> newPostList = response.body().getData();
                    // 在这里使用 newPostList 更新 UI 或执行其他操作
                    // 添加新数据到已有数据列表
                    postList.addAll(newPostList);
                    // 通知适配器数据集发生变化
                    if (adapter == null) {
                        // 如果适配器为空，说明是第一次加载数据，需要创建适配器
                        adapter = new MyPostsAdapter(postList, requireContext());
                        recyclerView.setAdapter(adapter);
                    }
                    // 如果适配器不为空，说明已经有数据，直接通知适配器数据变化
                    adapter.notifyDataSetChanged();
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<Post>>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    /**
     * 刷新数据，重新加载
     */
    private void refreshData() {
        // Reset max and offset for a fresh load
        current = 1;
        // Clear the existing data
        postList.clear();
        // Load new data
        loadMoreData();
        swipeRefreshLayout.setRefreshing(false);
    }



}
